package com.weifly.weistock.core.util;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期工具类
 *
 * @author weifly
 * @since 2020/12/02
 */
public class DateUtils {

    public static final String FORMATTER_DATE = "yyyyMMdd";
    public static final String FORMATTER_TIME = "HH:mm:ss";

    public static String formatTime(Date date) {
        return new SimpleDateFormat(FORMATTER_TIME).format(date);
    }

    public static Date parseDate(String pattern, String dateStr) {
        return parseDate(new SimpleDateFormat(pattern), dateStr);
    }

    public static Date parseDate(SimpleDateFormat sdf, String dateStr) {
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static String checkDateString(String dateStr) {
        if (StringUtils.isBlank(dateStr)) {
            return "不能为空";
        }
        if (dateStr.length() != 8) {
            return "长度应是8";
        }
        int year = Integer.parseInt(dateStr.substring(0, 4));
        int month = Integer.parseInt(dateStr.substring(4, 6));
        int day = Integer.parseInt(dateStr.substring(6, 8));
        if (year < 2010 || year > 2100) {
            return "year应在2010至2100之间";
        }
        if (month < 01 || month > 12) {
            return "month应在01至12之间";
        }
        Calendar cale = Calendar.getInstance();
        cale.set(Calendar.YEAR, year);
        cale.set(Calendar.MONTH, month - 1);
        int maxDay = cale.getActualMaximum(Calendar.DAY_OF_MONTH);
        if (day < 1 || day > maxDay) {
            return "day应在1至" + maxDay + "之间";
        }
        return null;
    }
}
